package com.example.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * TODO: 这里要写注释的!
 */
public class EchoServerHandler extends ChannelHandlerAdapter {
    int counter= 0;
    private static final SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String body= (String) msg;
        System.out.println("this is "+ ++counter+" times receive client : [ "+body+" ]");
        String date= dateFormat.format(new Date())+"$_";
        TimeUnit.MILLISECONDS.sleep(500);
        ByteBuf byteBuf= Unpooled.copiedBuffer(date.getBytes());
        ctx.writeAndFlush(byteBuf);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext var1, Throwable var2) throws Exception{
        var2.printStackTrace();
        var1.close();
    }

}